package it.polimi.registration.gui.security;

import it.polimi.registration.business.security.boundary.CalendarManager;
import it.polimi.registration.business.security.boundary.EventManager;
import it.polimi.registration.business.security.boundary.NotificationManager;
import it.polimi.registration.business.security.boundary.UserManager;
import it.polimi.registration.business.security.entity.BadWeather;
import it.polimi.registration.business.security.entity.Invitation;
import it.polimi.registration.business.security.entity.Notification;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Named
@RequestScoped
public class NotifBean {

    @PersistenceContext
    EntityManager enm;
    
	@Inject
	private Logger logger;

	@EJB
	private UserManager um;

	@EJB
	private CalendarManager cm;
    
    @EJB
    private NotificationManager nm;

	@EJB
	private EventManager em;

	public NotifBean() {

	}
	
	public boolean getIsOwner(Notification n) {
		return um.getLoggedUser().equals(n.getEvent().getOwner());
	}
	
	public String markAsRead(Notification n) {
		n.setRead(true);
		nm.merge(n);
    	return "/user/notifs.xhtml?faces-redirect=true";
	}
	
	public String acceptInvitation(Notification n) {
		((Invitation) n).accept();
		nm.merge(n);
    	return "/user/notifs.xhtml?faces-redirect=true";
	}
	
	public String declineInvitation(Notification n) {
		((Invitation) n).decline();
		nm.merge(n);
		
		um.getLoggedUser().declineEvent(n.getEvent());
		cm.merge(um.getLoggedUser().getCalendar());
		um.merge(um.getLoggedUser());
		em.merge(n.getEvent());
		
    	return "/user/notifs.xhtml?faces-redirect=true";
	}
	
	public String acceptBadWeather(Notification n) {
		((BadWeather) n).accept();
		nm.merge(n);
		em.merge(n.getEvent());
    	return "/user/notifs.xhtml?faces-redirect=true";
	}
	
	public String declineBadWeather(Notification n) {
		((BadWeather) n).decline();
		nm.merge(n);
    	return "/user/notifs.xhtml?faces-redirect=true";
	}
}
